package dd.lo.practice;

import dd.lo.util.ImageUtils;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.io.ByteArrayInputStream;
import java.io.File;

public class CornerDetectionDisplay extends Application {

    public static void start(String[] args) {
        launch(args);
    }

    private static final int DEFAULT_WIDTH = 1200;
    private static final int DEFAULT_HEIGHT = 900;

    private static final int SHOW_IMG_WIDTH = 600;
    private static final int SHOW_IMG_HEIGHT = 450;

    private Mat srcImg;

    private ImageView srcImageView;
    private ImageView harrisResultView;

    private void imageProcess() {
        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() {
                if (null == srcImg || srcImg.empty()) return null;
                //显示原图
                Platform.runLater(() -> showImage(new Mat(srcImg, new Rect(0, 0, srcImg.width(), srcImg.height())), srcImageView, "原图"));

                //Harris角点检测法
                Mat grayImg = new Mat();
                if (srcImg.channels() > 1) {
                    Imgproc.cvtColor(srcImg, grayImg, Imgproc.COLOR_BGR2GRAY);
                } else {
                    Core.copyTo(srcImg, grayImg, new Mat());
                }
                Mat harrisCornerResult = new Mat();
                Imgproc.cornerHarris(grayImg, harrisCornerResult, 2, 3, 0.01);
                Imgproc.threshold(harrisCornerResult, harrisCornerResult, 0.00001, 255, Imgproc.THRESH_BINARY);
                Platform.runLater(() -> showImage(new Mat(harrisCornerResult, new Rect(0, 0, harrisCornerResult.width(), harrisCornerResult.height())), harrisResultView, "Harris角点检测法结果"));

                return null;
            }
        };
        new Thread(task).start();
    }

    private void showImage(Mat img, ImageView view, String winTitle) {
        //缩放、转码
        ImageUtils.fitImgSize(img, SHOW_IMG_WIDTH, SHOW_IMG_HEIGHT);
        MatOfByte buffer = new MatOfByte();
        Imgcodecs.imencode(".jpeg", img, buffer);
        view.setImage(new Image(new ByteArrayInputStream(buffer.toArray())));
        //贴到组件上
        VBox vBox = new VBox();
        vBox.getChildren().addAll(view);
        Scene scene = new Scene(vBox, SHOW_IMG_WIDTH, SHOW_IMG_HEIGHT);
        Stage newWindow = new Stage();
//        newWindow.initModality(Modality.APPLICATION_MODAL); // 设置此模式，则窗口打开时，其他窗口无法操作
        newWindow.initModality(Modality.NONE);
        newWindow.setTitle(winTitle);
        newWindow.setScene(scene);
        newWindow.show();
    }

    @Override
    public void start(Stage stage) throws Exception {
        Button imgChooserBtn = new Button("选择图片");
        imgChooserBtn.setOnMouseClicked(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择图片");
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home") + "/Downloads")
            );
            fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("All Images", "*.*"));
            File imgFile = fileChooser.showOpenDialog(stage);
            if (null == imgFile) return;
            srcImg = Imgcodecs.imread(imgFile.getAbsolutePath(), Imgcodecs.IMREAD_UNCHANGED);
            if (srcImg.empty()) System.out.println("图片读取失败");
            imageProcess();
        });
        //关闭按钮
        Button exitBtn = new Button("关闭");
        exitBtn.setOnMouseClicked(e -> Platform.exit());
        VBox rows = new VBox(0);
        rows.setPadding(new Insets(10, 10, 0, 10));
        HBox row0 = new HBox(10);
        row0.setPadding(new Insets(5, 0, 5, 0));
        row0.getChildren().addAll(imgChooserBtn, exitBtn);
        rows.getChildren().addAll(row0);
        srcImageView = new ImageView();
        harrisResultView = new ImageView();
        HBox imgRow = new HBox(10);
        imgRow.setPadding(new Insets(10, 0, 10, 0));
        imgRow.getChildren().addAll(srcImageView);
        BorderPane root = new BorderPane();
        root.setCenter(imgRow);
        root.setBottom(rows);
        Scene scene = new Scene(root, DEFAULT_WIDTH, DEFAULT_HEIGHT + 50);
        stage.setScene(scene);
        stage.setTitle("角点检测演示");
        stage.setResizable(false);
        stage.show();
    }
}
